package org.example.mpplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mpplus.entity.User;
import org.example.mpplus.mapper.UserMapper;
import org.example.mpplus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public IPage<User> selectUserPage(Integer page, Integer pageSize) {
        IPage<User> userPage = new Page<>(page, pageSize);
        page(userPage);
        return userPage;
    }

    @Override
    public List<User> selectByWrapper(List<Integer> ages) {
       QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> ge = queryWrapper.
                in("age",ages)
                ;
        List<User> list = list(queryWrapper);
        return list;
    }

    @Override
    public Integer getMaxAge(String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> wrapper = queryWrapper.groupBy("password").select("max(age) age")
                .last("limit 1");
        List<User> list = list(queryWrapper);
        return list.get(0).getAge();
    }
    //使用lambda表达式代替表字段
    @Override
    public List<User> selectByWrapper() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> wrapper = queryWrapper.like(true, User::getName, "张")
                .orderByDesc(User::getAge);
        List<User> list = list(queryWrapper);
        return list;
    }

    @Override
    public List<Map<String, Object>> get() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> wrapper = queryWrapper.groupBy("age")
                .select("age,count(*) count");
        List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
        return maps;
    }

    @Override
    public User getOne(String name, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,name).eq(User::getPassword,password);
        User user = userMapper.selectOne(queryWrapper,false);
        return user;
    }
}
